<template>
  <PlayGround v-if="$store.state.pk.status === 'playing'"/>
  <MatchGround v-if="$store.state.pk.status === 'matching'"/>
  <ResultBoard v-if="$store.state.pk.loser !='none'"/>
</template>

<script>
import PlayGround from "@/components/PlayGround";
import {onMounted, onUnmounted} from 'vue'
import {useStore} from 'vuex'
import MatchGround from "@/components/MatchGround";
import ResultBoard from '@/components/ResultBoard'

export default {
  name: "PkIndexView",
  components: {
    ResultBoard,
    MatchGround,
    PlayGround,
  },
  setup() {
    let store = useStore();     //引用数据
    let socketUrl = `ws://localhost:3000/websocket/${store.state.user.token}/`;
    let socket = null;

    //状态更新
    store.commit("updateLoser", "none");

    // onMounted: 当组件被挂载的时候执行的函数
    onMounted(() => {

      //初始化一个对手用户信息
      store.commit("updateOpponent", {
        username: "我的对手",
        photo: "https://cdn.acwing.com/media/article/image/2022/08/09/1_1db2488f17-anonymous.png",
      })

      //连接的操作
      socket = new WebSocket(socketUrl);
      socket.onopen = () => {       //连接成功时调用的函数
        console.log("前端连接成功");
        store.commit("updateSocket", socket);
      }

      socket.onmessage = msg => {    //前端接收到消息时调用的函数(后端的sendMessage方法)
        let data = JSON.parse(msg.data);
        console.log("接收消息成功", data);
        if (data.event === "start matching") {
          //1.更新三个地方(pk的敌人照片、用户名和当前匹配的状态)
          store.commit("updateOpponent", {
            username: data.username,
            photo: data.photo,
          });
          setTimeout(() => {
            store.commit("updateStatus", "playing");
          }, 200);

          //2.更新地图
          store.commit("updateGame", data.game);
        } else if (data.event === "move") {
          console.log(data);
          const game = store.state.pk.gameObject;
          let [snake0, snake1] = game.snakes;
          snake0.set_direction(data.a_direction);
          snake1.set_direction(data.b_direction);
        } else if (data.event === "result") {
          console.log(data);

          //根据后端返回的数据判断输赢
          const game = store.state.pk.gameObject;
          let [snake0, snake1] = game.snakes;
          if (data.loser === 'all' || data.loser === "A")
            snake0.status = "die";
          else if (data.loser === "all" || data.loser === "B")
            snake1.status = "die";

          store.commit("updateLoser", data.loser);
        }
      }

      socket.onclose = () => {
        console.log("关闭连接成功");
      }
    })

    // onUnmounted : 当组件被卸载的时候执行的函数
    onUnmounted(() => {
      socket.close();
      store.commit("updateStatus", "matching");
    })
  }
}
</script>

<style scoped>

</style>